package com.dgut.controller;

import com.dgut.Service.DataService;
import com.dgut.model.ModelParams;
import com.dgut.model.RegionConfirm;
import com.dgut.model.SearchParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Controller
class ShowController {
    @Autowired
    private DataService service;

    @RequestMapping("/getData")
    public String searchData(SearchParams params, Model model){
        List<RegionConfirm> regionConfirms = service.getAllRegionConfirms();
        Set<String> provinces = new HashSet<>();
        Set<String> countries = new HashSet<>();
        ModelParams modelParams = new ModelParams();  //传送到前端的数据
        List<RegionConfirm> confirms = new ArrayList<>();
        boolean flag = false;   //是否有查询条件

        for (RegionConfirm regionConfirm : regionConfirms) {
            provinces.add(regionConfirm.getState());
            countries.add(regionConfirm.getCountry());
        }
        modelParams.setProvinces(provinces);
        modelParams.setCountries(countries);
        if(params.getProvince()==null&&params.getRegion()==null){  //首次访问页面 或 查询不带参数
            modelParams.setProvince("-1");
            modelParams.setRegion("-1");
        }
        else{  //非首次访问
            //查询条件按 并集 处理
            if(params.getProvince()!=null && !params.getProvince().equals("-1")){
                flag = true;
                for (RegionConfirm regionConfirm : regionConfirms) {
                    if(regionConfirm.getState().equals(params.getProvince())){
                        confirms.add(regionConfirm);
                    }
                }
            }
            if(params.getRegion()!=null && !params.getRegion().equals("-1")){
                flag =true;
                for (RegionConfirm regionConfirm : regionConfirms) {
                    if(regionConfirm.getCountry().equals(params.getRegion())){
                        confirms.add(regionConfirm);
                    }
                }
            }
            //设置回显参数
            if (params.getProvince() == null) {
                modelParams.setProvince("-1");
            } else {
                modelParams.setProvince(params.getProvince());
            }
            if (params.getRegion() == null) {
                modelParams.setRegion("-1");
            } else {
                modelParams.setRegion(params.getRegion());
            }
        }
        if(!flag){
            confirms = regionConfirms;
        }
        modelParams.setConfirms(confirms);
        model.addAttribute(modelParams);
        return "index";
    }

}
